/***********************************************************
 *  File_Name  : XJHexString.cpp
 *  File_Path   : 
 *  File_Encode : UTF8
 *  Description : Hexadecimal <==> AscII Class
 *  
 *  OS : Linux, UNIX,Windows,Other
 *  LastVersion  : 20111122
 *      
 *  Author      : LiXiujie(李秀杰)
 *  Date        : 2011-11-22
 *  Version     : 20111122
 *  Description : 
 *                
 *  Edit Author : 
 *  Edit Date   : 
 *  Version     : 
 *  Description :
 *                
 ***********************************************************/

#include "XJHexString.h"

namespace XJUtilClass{

XJHexString::XJHexString() {
	// TODO Auto-generated constructor stub

}

XJHexString::~XJHexString() {
	// TODO Auto-generated destructor stub
}
bool XJHexString::AscToHex(const unsigned char *szAscStr, const unsigned long nAscStrLen,
		char *szHexStr, unsigned long &nHexStrMaxSizeOrLen){
	const char szHexAlphabet[] = "0123456789ABCDEF";
	unsigned long i, nPos = 0;
	unsigned char ch;
	for (i=0;i < nAscStrLen;++i){
		ch = szAscStr[i];
		if (nPos < nHexStrMaxSizeOrLen){
			szHexStr[nPos++] = szHexAlphabet[((ch >> 4) & 0x0F)];
		} else {
			break;
		}
		if (nPos < nHexStrMaxSizeOrLen){
			szHexStr[nPos++] = szHexAlphabet[ch & 0x0F];
		} else {
			break;
		}
	}
	nHexStrMaxSizeOrLen = nPos;
	return true;
}
bool XJHexString::HexToAsc(const char *szHexStr, const unsigned long nHexStrLen,
		unsigned char *szAscStr, unsigned long &nAscStrMaxSizeOrLen){
	//const char szHexAlphabet[] = "0123456789ABCDEF";
	unsigned long i, nPos = 0;
	unsigned char ch;
	for (i=0;i < nHexStrLen;++i){
		ch = szHexStr[i];
		if (ch >= '0' && ch <= '9'){
			ch = ch - '0';
		} else if (ch >= 'A' && ch <= 'F'){
			ch = ch - 'A' + 10;
		} else if (ch >= 'a' && ch <= 'f'){
			ch = ch - 'a' + 10;
		} else {
			break;
		}
		if (nPos < nAscStrMaxSizeOrLen){
			if ((i+1)%2 == 1){
				szAscStr[nPos] = (ch << 4) & 0xF0;
			} else if ((i+1)%2 == 0){
				szAscStr[nPos] = szAscStr[nPos] | (ch & 0x0F);
				++nPos;
			}
		} else {
			break;
		}
	}
	if (nPos * 2 < nAscStrMaxSizeOrLen){
		++nPos;
	}
	nAscStrMaxSizeOrLen = nPos;
	return true;
}

} /* namespace XJUtilClass */
